/*
 * Copyright 2023-2085 xujin <ceo@itgrail.com>
 *
 * Licensed under the Grail License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://itgrail.com/docs?id=3&catalogId=87
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.itgrail.pilot.app.command.query;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Preconditions;
import com.itgrail.pilot.app.command.cmo.query.ListMyOKRCmd;
import com.itgrail.pilot.app.command.co.*;
import com.itgrail.pilot.app.converter.KeyResultClientConverter;
import com.itgrail.pilot.app.converter.ObjectiveClientConverter;
import com.itgrail.pilot.app.converter.OkrPeriodClientConverter;
import com.itgrail.pilot.domain.user.contant.OkrConstants;
import com.itgrail.pilot.infrastructure.tunnel.db.dao.*;
import com.itgrail.pilot.infrastructure.tunnel.db.dataobject.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import com.itgrail.grail.cqrs.annotation.CmdHandler;
import com.itgrail.grail.cqrs.command.CommandExecutorI;
import com.itgrail.grail.dto.ResultData;
import com.itgrail.grail.exception.BusinessException;
import com.itgrail.grail.utils.reflect.BeanMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@CmdHandler
public class ListMyOKRCmdExe implements CommandExecutorI<ResultData<OkrDetailCO>, ListMyOKRCmd> {

    @Autowired
    private OkrPeriodMapper okrPeriodMapper;

    @Autowired
    private ObjectiveMapper mapper;

    @Autowired
    private KeyResultMapper keyResultMapper;

    @Autowired
    private ObjectiveClientConverter objectiveClientConverter;

    @Autowired
    private KeyResultClientConverter keyResultClientConverter;

    @Autowired
    private OkrPeriodClientConverter okrPeriodClientConverter;

    @Autowired
    private UserOkrAlignMapper userOkrAlignMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClassifyMapper classifyMapper;

    @Override
    public ResultData execute(ListMyOKRCmd cmd) {
        ResultData resultData = ResultData.success(null);
        check(cmd);
        //查询该周期下  当前用户的所有对齐的okr
        List<UserOkrAlignDO> userAcceptOkrs = findUserAcceptOkrs(cmd);
        Map<Integer, List<UserOkrAlignDO>> map = userAcceptOkrs.stream().collect(Collectors.groupingBy(UserOkrAlignDO::getStartObjectiveId));
        List<OkrTreeCO> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(map)) {
            for (Map.Entry<Integer, List<UserOkrAlignDO>> entry : map.entrySet()) {
                Integer startObjectiveId = entry.getKey();
                List<UserOkrAlignDO> bindOkrs = entry.getValue();
                OkrTreeCO treeCO = new OkrTreeCO();
                List<OkrDetailCO> alignOkrs = new ArrayList<>();
                //拿到对齐人的okr 绑定当前用户的okr
                OkrDetailCO myOkrDetail = findDetail(startObjectiveId);
                UserCO currentUserInfo = getUserInfo(cmd.getUserId());
                //找到当前OKR对齐的所有OKR
                if (!CollectionUtils.isEmpty(bindOkrs)) {
                    bindOkrs.forEach(x -> {
                        Integer bindOkrId = x.getAcceptObjectiveId();
                        OkrDetailCO detail = findDetail(bindOkrId);
                        UserCO userInfo = getUserInfo(x.getAcceptUserId());
                        detail.setUserCO(userInfo);
                        alignOkrs.add(detail);
                    });
                }
                treeCO.setAlignOkrs(alignOkrs);
                treeCO.setMyOkrDetail(myOkrDetail);
                treeCO.setUserCO(currentUserInfo);
                list.add(treeCO);
            }
        }
        resultData.setData(list);
        return resultData;
    }

    protected boolean check(ListMyOKRCmd cmd) {
        Preconditions.checkNotNull(cmd, "cmd不能为null");
        Preconditions.checkNotNull(cmd.getOkrPeriodId(), "周期id不能为null");
        return true;
    }

    /**
     * 封装okr详情
     *
     * @param objectiveId
     * @return
     */
    protected OkrDetailCO findDetail(Integer objectiveId) {
        OkrDetailCO okrDetailCO = new OkrDetailCO();
        //获取目标信息
        ObjectiveDO objectiveDO = mapper.selectById(objectiveId);
        ObjectiveDetailCO objectiveDetailCO = objectiveClientConverter.dataToClient(objectiveDO);
        ClassifyDO classifyDO = classifyMapper.selectById(objectiveDO.getClassifyId());
        if (null != classifyDO) {
            objectiveDetailCO.setClassifyName(classifyDO.getName());
        }
        okrDetailCO.setObjectiveDetailCO(objectiveDetailCO);
        if (objectiveDO == null) {
            throw new BusinessException("500", "没有查询到OKR内容");
        }
        //获取考核周期实体
        OkrPeriodDO okrPeriodDO = okrPeriodMapper.selectById(objectiveDO.getOkrPeriodId());
        OkrPeriodDetailCO okrPeriodDetailCO = okrPeriodClientConverter.dataToClient(okrPeriodDO);
        okrDetailCO.setOkrPeriodDetailCO(okrPeriodDetailCO);

        //获取关键成果
        QueryWrapper<KeyResultDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", OkrConstants.NOT_DELETED);
        queryWrapper.eq("objective_id", objectiveId);
        List<KeyResultDO> keyResultDOS = keyResultMapper.selectList(queryWrapper);
        List<KeyResultDetailCO> keyResultDetailCOS = keyResultClientConverter.dataToClients(keyResultDOS);
        okrDetailCO.setKeyResultDetailCO(keyResultDetailCOS);
        return okrDetailCO;
    }

    /**
     * 查询用户当前周期下的所有对齐的他人的okr
     *
     * @param cmd
     * @return
     */
    protected List<UserOkrAlignDO> findUserAcceptOkrs(ListMyOKRCmd cmd) {
        QueryWrapper<UserOkrAlignDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", OkrConstants.NOT_DELETED);
        queryWrapper.eq("okr_period", cmd.getOkrPeriodId());
        queryWrapper.eq("start_user_id", cmd.getUserId());
        return userOkrAlignMapper.selectList(queryWrapper);
    }

    protected UserCO getUserInfo(Integer userId) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserDO userDO = userMapper.selectOne(queryWrapper);
        return BeanMapper.map(userDO, UserCO.class);
    }

}
